package gui.common;

import gui.GuiCommon;
import gui.client.Client;
import gui.common.msg.MsgType;
import gui.common.msg.SysMessage;
import gui.server.Server;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import server.DataServer;

import client.DataClient;

import data.User;

public class LoginDialogueListener implements ActionListener{
	
	private LoginDialogue loginDialogue;
	private DataClient dataClient=null;
	
	private BaseClientFrame bc=null;
	public LoginDialogueListener(LoginDialogue g,BaseClientFrame b) {
		this.loginDialogue=g;
		bc=b;
		dataClient=b.getDataClient();
		
		
	}
	public void actionPerformed(ActionEvent event) {
		SysMessage msg=new SysMessage();
		msg.subject="User Login";
		String password=loginDialogue.getPassword();
		String username=loginDialogue.getUserName();
		if(username.length()<1){
			msg.detail="Please Enter Username";
			
		}else if(password.length()<1){
			msg.detail="Please Enter Password";
			
		}else{
			DataServer dataServer=dataClient.getRemoteServer();
			if(dataServer!=null){
				try {
					SysMessage result=dataClient.getRemoteServer().loginUser(username, password);
					if(result.data!=null){
						User user=(User)result.data;
						if(user.getState()==1){
							dataClient.setCurrentUser(user);
							msg.detail="User:"+user.getUsername()+" login!";
						
							DefaultGroupList gp=(DefaultGroupList)bc.getContent();
							gp.showButtonAfterLogin();
						}else{
							msg.detail="Sorry,you account has been locked!";
						}
						loginDialogue.dispose();
					}else{
						msg.detail="No such user!";
					}
				} catch (Exception e) {
					e.printStackTrace();

				}
			}else{
				msg.detail="Please Connect Server first";
			}
		}
		
		GuiCommon.showAlertWindow(msg);
		
	}

}
